const webpack = require("webpack");
const glob = require("glob");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

const webpackConfig = {
  entry: {},
  output: {
    path: path.resolve(__dirname, "./dist/"),
    filename: "js/[name].[chunkhash:6].js",
    chunkFilename: "chunk/[name].[chunkhash:6].js",
  },
  devServer: { inline: true, port: 8181 },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        query: { presets: ["env", "react", "stage-2"] }
      },
      {
        test: /\.(less|css)$/,
        use: ["style-loader", "css-loader", "less-loader"]
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        loader: "url-loader?limit=8192&name=images/[hash:8].[name].[ext]"
      }
    ]
  },
  plugins: [],
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: "common",
          chunks: "all"
        }
      }
    }
  }
};
function getEntries(globPath) {
  const files = glob.sync(globPath),
    entries = {};
  files.forEach(function(filepath) {
    const split = filepath.split("/");
    const name = split[split.length - 2];
    entries[name] = "./" + filepath;
  });
  return entries;
}
const entries = getEntries("src/**/*.page.jsx");
Object.keys(entries).forEach(function(name) {
  webpackConfig.entry[name] = entries[name];
  const plugin = new HtmlWebpackPlugin({
    filename: name + ".html",
    template: "./public/index.html",
    inject: true,
    chunks: ["common", name]
  });
  webpackConfig.plugins.push(plugin);
});

module.exports = webpackConfig;
